package medium前K个高频数;

import java.util.*;

public class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        int[] top = new int[k];
        Map<Integer, Integer> map = new HashMap<>();
        for (int num:
                nums) {
            int i = map.getOrDefault(num, 0);
            map.put(num, i+1);
        }
        List<Map.Entry<Integer,Integer>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list,new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o2.getValue()-o1.getValue(); //重写排序规则，小于0表示升序，大于0表示降序
            }
        });
        Iterator<Map.Entry<Integer, Integer>> iter = list.iterator();
        int j = 0;
        while(iter.hasNext()){
            Map.Entry<Integer, Integer> item = iter.next();
            int key = item.getKey();
            top[j] = key;
            j++;
            if (j > k)
                break;
        }
        return top;
    }

}
